from urllib.parse import quote
from datetime import datetime, timedelta
from core.logger import app_logger as logger
import subprocess


def parse_channel_from_task_session(task_session):
    """从TaskSession中提取通道号（去掉首字母D）"""
    if task_session and task_session.startswith('D'):
        try:
            return int(task_session[1:])
        except ValueError:
            return 0
    return 0

def generate_rtsp_url(ip, port, username, password, channel, start_time, end_time, stream_type="main"):
    """生成RTSP回放URL"""
    stream_code = "01" if stream_type.lower() == "main" else "02"
    track_id = f"{channel}{stream_code}"
    
    def convert_time(time_str):
        ymd, hms = time_str.split(" ")
        return ymd.replace("-", "") + "T" + hms.replace(":", "") + "Z"
    
    start_utc = convert_time(start_time)
    end_utc = convert_time(end_time)
    
    safe_username = quote(username, safe="")
    safe_password = quote(password, safe="")
    
    url = (
        f"rtsp://{safe_username}:{safe_password}@{ip}:{port}/"
        f"Streaming/tracks/{track_id}?"
        f"starttime={start_utc}&endtime={end_utc}"
    )

    logger.info(f"生成url: {url}")
    
    return url

def get_playback_url(alarm, username="admin", password="aa147258"):
    """根据告警生成回放URL"""
    try:
        # 从TaskSession提取通道号
        if not alarm.TaskSession or not alarm.TaskSession.startswith('D'):
            raise ValueError("无效的TaskSession格式")
            
        channel = parse_channel_from_task_session(alarm.TaskSession)
        
        # 计算回放时间范围
        alarm_time = alarm.CreateTime
        start_time = (alarm_time - timedelta(seconds=5)).strftime("%Y-%m-%d %H:%M:%S")
        end_time = (alarm_time + timedelta(seconds=5)).strftime("%Y-%m-%d %H:%M:%S")
        
        return generate_rtsp_url(
            ip="192.168.10.200",  # 注意这里写死了
            port=554,
            username=username,
            password=password,
            channel=channel,
            start_time=start_time,
            end_time=end_time,
            stream_type="main"
        )
    except Exception as e:
        print(f"生成回放URL失败: {str(e)}")
        return None